<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>downloadByAnchor</title>
</head>

<body>
    <button type="button" id="downloadBtn">点击我下载url文件</button>
    <button type="button" id="downloadDataBtn">点击我下载数据文件</button>
    <script>
        const downloadByAnchor = (urlOrData, fileName) => {
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = typeof urlOrData === 'string' ? urlOrData : URL.createObjectURL(new Blob([JSON.stringify(urlOrData)]));
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        };
        const btn1 = document.querySelector('#downloadBtn');
        const btn2 = document.querySelector('#downloadDataBtn');
        btn1.addEventListener('click', () => {
            downloadByAnchor('./downloadByAnchor.html', 'downloadByAnchor.html');
        })
        btn2.addEventListener('click', () => {
            downloadByAnchor({ a: 1, b: 1 }, 'test.json')
        })
    </script>
</body>

</html>